package com.example.demo12.myservlet;

import com.example.demo12.dbdatabase;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private String dbUrl = "jdbc:mysql://localhost:3306/mywebapp";
    private String dbUsername = "root";
    private String dbPassword = "123126";
    private dbdatabase dbdatabase;
    private Connection connection;

    public LoginServlet() throws SQLException, ClassNotFoundException {
        dbdatabase = new dbdatabase();
        connection = dbdatabase.getConnection();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            if (authenticate(username, password)) {
                HttpSession session = request.getSession();
                session.setAttribute("user", username);
                response.sendRedirect("products");
            } else {
                System.out.println("未登录成功");
                response.sendRedirect(request.getContextPath() + "/login.jsp?error=用户名或密码错误，请重新输入");
            }
        } catch (SQLException e) {
            System.out.println("出现异常");
            e.printStackTrace();
        }
    }

    private boolean authenticate(String username, String password) throws SQLException {
        String query = "SELECT * FROM users WHERE username = ? AND password = ?";
        PreparedStatement pstmt = connection.prepareStatement(query);

        pstmt.setString(1, username);
        pstmt.setString(2, password);

        ResultSet rs = pstmt.executeQuery();
        return rs.next();
    }

    @Override
    public void destroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}